<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>越南时事新闻汉越双语平行语料库 - 语料库管理</title>
    <link rel="stylesheet" href="css/common.css">
    <style>
        body {
            font-family: 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
        }

        /* 顶部导航栏 */
        .header {
            background: #c41e3a;
            color: white;
            padding: 0 20px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 18px;
            font-weight: bold;
        }

        .logo::before {
            content: "🏛️";
            margin-right: 8px;
            font-size: 20px;
        }

        .nav-links {
            display: flex;
            gap: 20px;
        }

        .nav-links a {
            color: white;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 4px;
            transition: background 0.3s ease;
        }

        .nav-links a:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .nav-links a.active {
            background: rgba(255, 255, 255, 0.3);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-avatar {
            width: 32px;
            height: 32px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }

        .logout-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s ease;
        }

        .logout-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        /* 主内容区域 */
        .main-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 40px 20px;
        }

        /* 页面头部区域 */
        .page-header {
            background: white;
            border-radius: 12px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 40px;
        }

        .header-content {
            flex: 0 0 auto;
        }

        .header-actions {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 20px;
            align-items: flex-end;
        }

        .page-title {
            font-size: 28px;
            font-weight: bold;
            color: #c41e3a;
            margin-bottom: 8px;
        }

        .page-subtitle {
            font-size: 16px;
            color: #666;
        }

        /* 搜索和筛选区域 */
        .search-section {
            background: transparent;
            padding: 0;
            margin: 0;
            box-shadow: none;
        }

        .search-form {
            display: flex;
            gap: 15px;
            align-items: end;
            flex-wrap: wrap;
            justify-content: flex-end;
        }

        .search-group {
            flex: 0 0 auto;
            min-width: 160px;
        }

        .search-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }

        .search-input {
            width: 100%;
            padding: 10px 14px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: #c41e3a;
            box-shadow: 0 0 0 3px rgba(196, 30, 58, 0.1);
        }

        .search-btn {
            padding: 10px 20px;
            background: #c41e3a;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        .search-btn:hover {
            background: #a0172e;
            transform: translateY(-2px);
        }

        /* 语料库卡片网格 */
        .corpus-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 30px;
            margin-bottom: 40px;
        }

        .corpus-card {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 16px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
        }

        .corpus-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: #c41e3a;
        }

        .corpus-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 32px rgba(0,0,0,0.15);
        }

        .corpus-image {
            width: 100%;
            height: 120px;
            background: linear-gradient(135deg, #c41e3a 0%, #a0172e 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .corpus-image-actions {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            gap: 8px;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .corpus-card:hover .corpus-image-actions {
            opacity: 1;
        }

        .corpus-title-overlay {
            font-size: 18px;
            font-weight: bold;
            color: white;
            text-align: center;
            padding: 0 15px;
            line-height: 1.3;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .corpus-content {
            padding: 25px;
        }


        .corpus-description {
            color: #666;
            line-height: 1.6;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .corpus-meta {
            padding-top: 15px;
            border-top: 1px solid #e0e0e0;
        }

        .corpus-domain {
            display: inline-block;
            padding: 4px 12px;
            background: rgba(196, 30, 58, 0.1);
            color: #c41e3a;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .action-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .action-btn.small {
            padding: 4px 8px;
            font-size: 11px;
            border-radius: 3px;
        }

        .action-btn.primary {
            background: #c41e3a;
            color: white;
        }

        .action-btn.primary:hover {
            background: #a0172e;
        }

        .action-btn.secondary {
            background: #ffd700;
            color: #333;
        }

        .action-btn.secondary:hover {
            background: #e6c200;
        }

        .action-btn.danger {
            background: #dc3545;
            color: white;
        }

        .action-btn.danger:hover {
            background: #c82333;
        }

        /* 分页 */
        .pagination-section {
            display: flex;
            justify-content: center;
            margin-top: 40px;
        }

        .pagination {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .pagination button {
            padding: 10px 15px;
            border: 1px solid #e0e0e0;
            background: white;
            color: #666;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .pagination button:hover {
            background: #c41e3a;
            color: white;
            border-color: #c41e3a;
        }

        .pagination button.active {
            background: #c41e3a;
            color: white;
            border-color: #c41e3a;
        }

        .pagination button:disabled {
            background: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
        }

        /* 创建按钮 */
        .create-btn {
            padding: 12px 24px;
            background: #c41e3a;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            white-space: nowrap;
        }

        .create-btn:hover {
            background: #a0172e;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(196, 30, 58, 0.3);
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .main-container {
                padding: 20px;
            }

            .page-header {
                flex-direction: column;
                align-items: stretch;
                gap: 20px;
            }

            .header-actions {
                align-items: stretch;
            }

            .page-title {
                font-size: 24px;
            }

            .corpus-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }

            .search-form {
                flex-direction: column;
                align-items: stretch;
            }

            .search-group {
                min-width: auto;
            }

            .nav-links {
                display: none;
            }
        }

        /* 加载动画 */
        .loading {
            display: none;
            text-align: center;
            padding: 40px;
        }

        .loading-spinner {
            display: inline-block;
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #c41e3a;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <header class="header">
        <div class="logo">
            <span>越南时事新闻汉越双语平行语料库</span>
        </div>
        
        <nav class="nav-links">
            <a href="index.html">首页</a>
            <a href="corpus-libraries.html" class="active">语料库</a>
        </nav>

        <div class="user-info">
            <div class="user-avatar">👤</div>
            <span id="userName">用户</span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </header>

    <!-- 主内容区域 -->
    <main class="main-container">
        <!-- 页面头部区域 -->
        <section class="page-header">
            <div class="header-content">
                <h1 class="page-title">语料库管理</h1>
                <p class="page-subtitle">管理和浏览汉越双语平行语料库</p>
            </div>
            <div class="header-actions">
                <button class="create-btn" onclick="createCorpusLibrary()">
                    创建新语料库
                </button>
                <!-- 搜索和筛选区域 -->
                <div class="search-section">
                    <form class="search-form" id="searchForm">
                        <div class="search-group">
                            <label for="keyword">关键词搜索</label>
                            <input 
                                type="text" 
                                id="keyword" 
                                name="keyword" 
                                class="search-input" 
                                placeholder="输入语料库名称或描述"
                            >
                        </div>
                        <div class="search-group">
                            <label for="domain">领域筛选</label>
                            <select id="domain" name="domain" class="search-input">
                                <option value="">全部领域</option>
                                <option value="政治">政治</option>
                                <option value="经济">经济</option>
                                <option value="文化">文化</option>
                                <option value="科技">科技</option>
                                <option value="体育">体育</option>
                                <option value="社会">社会</option>
                                <option value="其他">其他</option>
                            </select>
                        </div>
                        <div class="search-group">
                            <label for="status">状态筛选</label>
                            <select id="status" name="status" class="search-input">
                                <option value="">全部状态</option>
                                <option value="active">活跃</option>
                                <option value="inactive">非活跃</option>
                                <option value="archived">已归档</option>
                            </select>
                        </div>
                        <button type="submit" class="search-btn">搜索</button>
                    </form>
                </div>
            </div>
        </section>

        <!-- 语料库卡片网格 -->
        <section class="corpus-grid" id="corpusGrid">
            <!-- 语料库卡片将通过JavaScript动态生成 -->
        </section>

        <!-- 分页 -->
        <section class="pagination-section">
            <div class="pagination" id="pagination">
                <!-- 分页按钮将通过JavaScript动态生成 -->
            </div>
        </section>

        <!-- 加载动画 -->
        <div class="loading" id="loading">
            <div class="loading-spinner"></div>
            <span style="margin-left: 10px;">加载中...</span>
        </div>
    </main>

    <script>
        // 页面加载时检查登录状态
        window.addEventListener('load', function() {
            checkLoginStatus();
            loadCorpusLibraries();
        });

        // 检查登录状态
        function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const user = localStorage.getItem('user');
            
            if (!token) {
                window.location.href = 'login.html';
                return;
            }
            
            if (user) {
                try {
                    const userData = JSON.parse(user);
                    document.getElementById('userName').textContent = userData.username || '用户';
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                }
            }
        }

        // 加载语料库列表
        async function loadCorpusLibraries(page = 1, keyword = '', domain = '', status = '') {
            const loading = document.getElementById('loading');
            const corpusGrid = document.getElementById('corpusGrid');
            
            loading.style.display = 'block';
            corpusGrid.innerHTML = '';

            try {
                // 构建查询参数
                const params = new URLSearchParams({
                    page: page,
                    size: 12,
                    keyword: keyword,
                    domain: domain
                });

                const response = await fetch(`/corpus/libraries/list?${params}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 200) {
                        displayCorpusLibraries(result.data);
                        updatePagination(result.data, page);
                    } else {
                        showError('加载语料库列表失败：' + result.msg);
                    }
                } else {
                    showError('网络错误，请稍后重试');
                }
            } catch (error) {
                console.error('加载语料库列表错误:', error);
                showError('加载失败，请稍后重试');
            } finally {
                loading.style.display = 'none';
            }
        }

        // 显示语料库列表
        function displayCorpusLibraries(data) {
            const corpusGrid = document.getElementById('corpusGrid');
            
            if (!data.records || data.records.length === 0) {
                corpusGrid.innerHTML = `
                    <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
                        <div style="width: 80px; height: 80px; background: #f0f0f0; border-radius: 8px; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center; font-size: 24px; color: #999;">库</div>
                        <h3>暂无语料库</h3>
                        <p>还没有创建任何语料库，点击上方按钮创建第一个语料库吧！</p>
                    </div>
                `;
                return;
            }

            corpusGrid.innerHTML = data.records.map(library => `
                <div class="corpus-card" onclick="viewCorpusLibrary('${library.id}')">
                    <div class="corpus-image">
                        <div class="corpus-title-overlay">${library.name}</div>
                        <div class="corpus-image-actions">
                            <button class="action-btn secondary small" onclick="event.stopPropagation(); editCorpusLibrary('${library.id}')" title="编辑">
                                ✏️
                            </button>
                            <button class="action-btn danger small" onclick="event.stopPropagation(); deleteCorpusLibrary('${library.id}', '${library.name}')" title="删除">
                                🗑️
                            </button>
                        </div>
                    </div>
                    <div class="corpus-content">
                        <p class="corpus-description">${library.description || '暂无描述'}</p>
                        <div class="corpus-meta">
                            <span class="corpus-domain">${library.domain || '未分类'}</span>
                        </div>
                    </div>
                </div>
            `).join('');
        }


        // 更新分页
        function updatePagination(data, currentPage) {
            const pagination = document.getElementById('pagination');
            const totalPages = Math.ceil(data.total / data.size);
            
            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }

            let paginationHTML = '';
            
            // 上一页按钮
            paginationHTML += `
                <button ${currentPage <= 1 ? 'disabled' : ''} onclick="loadCorpusLibraries(${currentPage - 1})">
                    上一页
                </button>
            `;

            // 页码按钮
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                paginationHTML += `
                    <button class="${i === currentPage ? 'active' : ''}" onclick="loadCorpusLibraries(${i})">
                        ${i}
                    </button>
                `;
            }

            // 下一页按钮
            paginationHTML += `
                <button ${currentPage >= totalPages ? 'disabled' : ''} onclick="loadCorpusLibraries(${currentPage + 1})">
                    下一页
                </button>
            `;

            pagination.innerHTML = paginationHTML;
        }

        // 搜索表单提交
        document.getElementById('searchForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const keyword = formData.get('keyword') || '';
            const domain = formData.get('domain') || '';
            const status = formData.get('status') || '';
            
            loadCorpusLibraries(1, keyword, domain, status);
        });

        // 查看语料库详情
        function viewCorpusLibrary(id) {
            // 跳转到语料库详情页面
            window.location.href = `corpus-library-detail.html?id=${id}`;
        }

        // 编辑语料库
        function editCorpusLibrary(id) {
            // 跳转到编辑页面
            window.location.href = `corpus-library-edit.html?id=${id}`;
        }

        // 创建语料库
        function createCorpusLibrary() {
            // 跳转到创建页面
            window.location.href = 'corpus-library-create.html';
        }

        // 删除语料库
        async function deleteCorpusLibrary(id, name) {
            if (!confirm(`确定要删除语料库"${name}"吗？\n\n注意：删除后将无法恢复，请谨慎操作！`)) {
                return;
            }

            try {
                const response = await fetch(`/corpus/libraries/delete/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    if (result.code === 200) {
                        alert('语料库删除成功！');
                        // 重新加载列表
                        loadCorpusLibraries();
                    } else {
                        showError('删除失败：' + result.msg);
                    }
                } else {
                    showError('网络错误，请稍后重试');
                }
            } catch (error) {
                console.error('删除语料库错误:', error);
                showError('删除失败，请稍后重试');
            }
        }

        // 退出登录
        async function logout() {
            if (confirm('确定要退出登录吗？')) {
                try {
                    // 调用后端登出接口
                    await fetch('/auth/logout', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('token')}`,
                            'Content-Type': 'application/json'
                        }
                    });
                } catch (error) {
                    console.error('登出请求失败:', error);
                } finally {
                    // 清除本地存储
                    localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    
                    // 跳转到登录页
                    window.location.href = 'login.html';
                }
            }
        }

        // 显示错误消息
        function showError(message) {
            alert('错误：' + message);
        }
    </script>
</body>
</html>
